#!/usr/bin/env python
# -*- coding: utf-8 -*-

# fichero de configuración
#CONFIGFILE = '/etc/meliponini/meliponini.conf'

import string,cgi,time,sys,os,json,hashlib,base64
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
from threading import Timer
from datetime import datetime
from urllib2 import Request, urlopen, URLError, HTTPError
import subprocess
from subprocess import Popen, PIPE

from config import Config
import handler
from httphandler import MeliponiniHTTPHandler
import socket

import smtplib
from email.mime.text import MIMEText

import logs

# configuración
config = Config()

def log(s):
    #print time.strftime(config.LOGDATETIMEFORMAT, time.localtime()), '-', s
    logs.log(s)

def adminmail(subject, content):
    try:
        msg = MIMEText(content)
        msg['Subject'] = subject
        msg['From'] = 'info@secuoyas.com'
        msg['To'] = config.ADMINEMAIL
        
        s = smtplib.SMTP()
        s.connect()
        s.sendmail(msg['From'], [email.strip(' ') for email in config.ADMINEMAIL.split(',')], msg.as_string())
        s.quit()
    except:
        log('ERROR sending email!')


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

'''
Función principal
'''
def main():
    # trata de arrancarlo!
    try:
        log( "listenning in port %d" % config.PORT )
        server = ThreadedHTTPServer(('', config.PORT), MeliponiniHTTPHandler)
        log( "running" )
        server.serve_forever();
    except KeyboardInterrupt:
        print '^C received, shutting down server...'
        server.socket.close()
        

if __name__ == "__main__":
    main()
